﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;

public class DeckCardSelectSceneManager : LTEventListenerC
{

    static public bool isMultySelect = true;
    static public bool isEnhance = true;
    static public List<UnitInfo> SelectCardInfos = new List<UnitInfo>();
    static public UnitInfo OrizinCard;


    int m_MaxCheckNum = 0;  //총 몇장 선택할수있는지;
    int m_CrrCheckNum = 0;

    public MyUnitCard selectedCardObject;
    MyUnitCard[] scrollCards;

    public MyUnitListManager listManager;

    public UILabel m_CheckLabel;
    public UILabel m_CrrCardNum;
    public UILabel m_MaxCardNum;
    public UILabel m_NeedMoney;

    public UILabel m_CardInfoTitle;
    public UILabel m_CardInfoBody;
    public GameObject m_CardInfoRoot;

    public GameObject[] m_CardKindButtons;
    public GameObject m_ThreeStarCheckBox;

    public GameObject[] m_TapButtons;

    public Transform m_ScrollView;
    public UIScrollBar m_ScrollBar;
    public UIGrid m_Grid;

    public UILabel m_Title;

    List<UnitInfo> m_UnitList;
    List<UnitInfo> m_ShowUnitList;

    //스크롤 관련
    Vector3 m_PreScrollViewPos;
    const int MaxNumOfCardDummys = 13;   // 회전시킬 카드 바운더리
    int m_FirstShowCardIndex = 0;
    int m_NumOfShowCards = 1;   //필터 이후 몇개의 카드가 표현되는지
    const int MaxNumOfShowCardsOnScreen = 5;

    enum SortingMode
    {
        GetTime,
        Level
    }

    SortingMode m_SortingMode = SortingMode.GetTime;
    SortingMode m_PreSortingMode = SortingMode.GetTime;
    element m_FilterMode = element.none;  // 전체
    element m_PreFilerMode = element.none; // 이전 정보


    void Awake()
    {
        m_PreScrollViewPos = m_ScrollView.localPosition;
        m_UnitList = MyInfo.Instance.MyUnitsList;   // 마이유닛 리스트 복사
        //AllUnitInfosUnCheck(m_UnitList);   // 모든 유닛 체크 해제
        SelectCardInfos.Clear(); //셀렉트 초기화
        m_ShowUnitList = new List<UnitInfo>();      // 필터링 한 카드들 모임     

        if (isMultySelect)
        {
            if (isEnhance)
                m_MaxCheckNum = 25;
        }
        else
            m_MaxCheckNum = 1;

        if (isEnhance)
            m_Title.text = "카드 강화";
        else
            m_Title.text = "카드 진화";

        GameObject Card1 = GameObject.Find("Card1");
        scrollCards = new MyUnitCard[MaxNumOfCardDummys];

        GameObject tempObj = null;
        for (int i = 0; i < scrollCards.Length; i++)  //씬에 들어있는 카드
        {
            if (i == 0)
            {
                tempObj = Card1;

                //콜라이더 크기 변경
                ((BoxCollider)tempObj.collider).size = new Vector3(275, 380, 0);

                tempObj.GetComponent<UIButtonMessage>().target = gameObject;
                tempObj.GetComponent<LTButtonMessage>().enabled = false;
            }
            else
            {
                tempObj = Instantiate(Card1) as GameObject;

                tempObj.transform.parent = Card1.transform.parent;
                tempObj.transform.localScale = Card1.transform.localScale;
            }

            scrollCards[i] = tempObj.GetComponent<MyUnitCard>();
        }


        m_CheckLabel.text = string.Format("{0} / {1}", 0, m_MaxCheckNum);


        UpdateUI();
        UpdateCards();
    }

    void UpdateUI()
    {
        m_CrrCardNum.text = MyInfo.Instance.MyUnitsList.Count.ToString();
        m_MaxCardNum.text = (CGSettingDataManager.Instance.GetInventoryExtendCount() + MyInfo.Instance.AdditionalInvenCount).ToString();

        if (!selectedCardObject.gameObject.activeSelf)
        {
            m_NeedMoney.text = "0";
            m_CardInfoRoot.SetActive(false);
        }
        else
        {
            m_NeedMoney.text = "0";

            CUnitData unitData = CUnitDataManager.Instance.GetUnitData(selectedCardObject._unitInfo.UnitClassID);
            if (unitData != null)
            {
                string[] splitSkillString = new string[0];
                if (!string.IsNullOrEmpty(unitData.passive_skill))
                    splitSkillString = unitData.passive_skill.Split(';');

                if (splitSkillString.Length > 0)
                {
                    m_CardInfoRoot.SetActive(true);
                    m_CardInfoTitle.text = CStringTableManager.Instance.GetItemByName(CSkillDataManager.Instance.FindSkillData(splitSkillString[0]).name_string);
                    m_CardInfoBody.text = CStringTableManager.Instance.GetItemByName(CSkillDataManager.Instance.FindSkillData(splitSkillString[0]).desc_string);
                }
                else
                {
                    m_CardInfoRoot.SetActive(false);
                    m_CardInfoTitle.text = "";
                    m_CardInfoBody.text = "";
                }
                //	            m_CardInfoTitle.text = selectedCardObject.cardName[0].text;
                //	            m_CardInfoBody.text = selectedCardObject.cardSkillDesc.text;
            }

            // 필터모드 적용
            switch (m_FilterMode)
            {
                case element.none:      //전체 보임
                    {
                    }
                    break;
                case element.sky:
                    {
                    }
                    break;
                case element.ocean:
                    {
                    }
                    break;
                case element.earth:
                    {
                    }
                    break;
            }

            if (m_PreFilerMode != m_FilterMode || m_PreSortingMode != m_SortingMode)     // 필터 또는 소팅 바뀌면 카드 업데이트
            {
                m_PreFilerMode = m_FilterMode;
                m_PreSortingMode = m_SortingMode;
                UpdateCards();
            }
        }
    }

    void UpdateCards()
    {
        m_ShowUnitList.Clear(); // 필터링 리스트
        foreach (UnitInfo info in m_UnitList)
        {
            if (OrizinCard != null)
            {
                if (OrizinCard == info)
                    continue;
            }

            if (isMultySelect && MyInfo.Instance.IsExistUnitInDeckMap(info.UnitDBID))
                continue;

            if (!isEnhance)  // 진화시 진화 가능 카드만 보여줌 (만랩 혹은 진화 가능여부 판단)
            {
                CUnitData crrCard = CUnitDataManager.Instance.GetUnitData(info.UnitClassID);
                if (info.UnitLevel != crrCard.max_lv || string.IsNullOrEmpty(crrCard.evolution_target))
                    continue;
            }

            if (m_FilterMode == element.none)
                m_ShowUnitList.Add(info);
            else if (info.element == m_FilterMode)
                m_ShowUnitList.Add(info);
        }

        m_NumOfShowCards = m_ShowUnitList.Count;

        //Debug.Log(m_NumOfShowCards);

        //m_ShowUnitList 소팅

        for (int i = 0; i < MaxNumOfCardDummys; i++)
        {
            if (i < m_NumOfShowCards)
            {
                // 셋 카드                
                SetCardInfo(scrollCards[(i + m_FirstShowCardIndex) % MaxNumOfCardDummys], m_ShowUnitList[i + m_FirstShowCardIndex]);
            }
            else
            {
                scrollCards[i].gameObject.SetActive(false);
            }
        }

        float size = 0;
        if (m_NumOfShowCards == 0)
            size = 1;
        else
        {
            size = MaxNumOfShowCardsOnScreen / (float)m_NumOfShowCards;
            if (size > 1)
                size = 1;
        }

        m_ScrollBar.barSize = size;
    }

    // Use this for initialization
    void Start()
    {
        //invenCountLabel.text = "("+MyInfo.Instance.MyUnitsList.Count + "/" + (CGSettingDataManager.Instance.GetInventoryExtendCount()+MyInfo.Instance.AdditionalInvenCount)+")";
    }


    //카드 클릭시
    void ClickedTeamCard(GameObject obj)
    {
        if (isMultySelect)
        {
            MyUnitCard selectCard = obj.GetComponent<MyUnitCard>();

            if (selectCard.IsCheck())
            {
                selectCard.SetCheck(false);
                SelectCardInfos.Remove(selectCard._unitInfo);
            }
            else
            {
                if (m_CrrCheckNum < m_MaxCheckNum)
                {
                    selectCard.SetCheck(true);
                    SelectCardInfos.Add(selectCard._unitInfo);

                    SetCardInfo(selectedCardObject, selectCard._unitInfo);
                    selectedCardObject.gameObject.SetActive(true);
                }
            }

            UpdateCheckCount();
        }
        else
        {
            MyUnitCard selectCard = obj.GetComponent<MyUnitCard>();
            SetCardInfo(selectedCardObject, selectCard._unitInfo);
            selectedCardObject.gameObject.SetActive(true);

            SelectCardInfos.Clear();
            SelectCardInfos.Add(selectCard._unitInfo);

            m_CheckLabel.text = string.Format("{0} / {1}", 1, 1);

            SelectCard(selectCard);
        }

        UpdateUI();
    }

    void UpdateCheckCount()
    {
        m_CrrCheckNum = 0;
        int money = 0;
        foreach (UnitInfo temp in m_ShowUnitList)
        {
            if (temp.isChecked)
            {
                m_CrrCheckNum++;
            }
        }

        m_CheckLabel.text = string.Format("{0} / {1}", m_CrrCheckNum, m_MaxCheckNum);
        m_NeedMoney.text = money.ToString();
    }


    void AllUnitInfosUnCheck(List<UnitInfo> list)  // 씬 초기화 및 씬 나갈때 체크 해제
    {
        foreach (UnitInfo temp in list)
        {
            temp.isChecked = false;
        }
    }

    void Update()
    {
        if (m_ScrollView.localPosition.x != m_PreScrollViewPos.x && m_NumOfShowCards > 0)
        {
            bool IsMoveRight = (m_PreScrollViewPos.x > m_ScrollView.localPosition.x);
            m_PreScrollViewPos = m_ScrollView.localPosition;

            bool isNeedCardPosChange = false;
            if (IsMoveRight && m_NumOfShowCards > m_FirstShowCardIndex + MaxNumOfCardDummys)
                isNeedCardPosChange = true;
            else if (!IsMoveRight && m_FirstShowCardIndex > 0)
                isNeedCardPosChange = true;


            if (isNeedCardPosChange)
            {
                for (int i = 0; i < MaxNumOfCardDummys; i++)
                {
                    if (IsMoveRight)
                    {
                        if (scrollCards[i].transform.position.x < -3.1f)
                        {
                            m_FirstShowCardIndex++;
                            Vector3 pos = scrollCards[i].transform.localPosition;
                            pos.x = (m_FirstShowCardIndex + MaxNumOfCardDummys - 1) * m_Grid.cellWidth;
                            scrollCards[i].transform.localPosition = pos;
                            SetCardInfo(scrollCards[i], m_ShowUnitList[m_FirstShowCardIndex + MaxNumOfCardDummys - 1]);
                        }
                    }
                    else
                    {
                        if (scrollCards[i].transform.position.x > 4.1f)
                        {
                            m_FirstShowCardIndex--;
                            Vector3 pos = scrollCards[i].transform.localPosition;
                            pos.x = m_FirstShowCardIndex * m_Grid.cellWidth;
                            scrollCards[i].transform.localPosition = pos;
                            SetCardInfo(scrollCards[i], m_ShowUnitList[m_FirstShowCardIndex]);
                        }
                    }
                }

                //m_ScrollBar.value = m_FirstShowCardIndex / (float)(m_NumOfShowCards - MaxNumOfShowCardsOnScreen);
            }
        }
    }

    void SetCardInfo(MyUnitCard card, UnitInfo info)
    {
        card.SetCardInfo(0, info);
        card.SetCheck(info.isChecked);
    }

    void OnClickedBackButton(GameObject obj)
    {
        SelectCardInfos.Clear();

        if (CSceneManager.prevSceneIndex == SCENE.UnitLevelupScene)
            CSceneManager.manager.GoToUnitLevelUpScene();
        else
            CSceneManager.manager.GoToUnitPowerUpScene();
    }

    void OnClickedOKButton(GameObject obj)
    {
        if (CSceneManager.prevSceneIndex == SCENE.UnitLevelupScene)
            CSceneManager.manager.GoToUnitLevelUpScene();
        else
            CSceneManager.manager.GoToUnitPowerUpScene();
    }

    void OnDestroy()   // 방나갈때 선택한 카드 없앰
    {
        OrizinCard = null;
    }

    void SelectCard(MyUnitCard selectCard)
    {
        foreach (MyUnitCard t in scrollCards)
        {
            t.CursorCard.SetActive(selectCard == t);
        }
    }
}
